package middol.Listener

import grails.converters.JSON
import grails.events.annotation.Subscriber
import grails.gorm.transactions.Transactional
import groovy.transform.CompileStatic
import middol.global.BusinessException
import middol.test.Test
import org.grails.datastore.mapping.engine.event.AbstractPersistenceEvent
import org.grails.datastore.mapping.engine.event.PostDeleteEvent
import org.grails.datastore.mapping.engine.event.PostInsertEvent
import org.grails.datastore.mapping.engine.event.PostUpdateEvent

/**
* @Description:    Test 实体类 监听服务
* @Author:         zhangjiayu@middol.com
* @CreateDate:     2020/10/23 10:11
* @Version:        1.0
*/
@CompileStatic
class TestListenerService {

    Test test(AbstractPersistenceEvent event){
        if ( event.entityObject instanceof Test ) {
            return (Test) event.entityObject
        }
        null
    }
    @Transactional
    @Subscriber
    void beforeInsert(PostInsertEvent event) {
        Test test = test(event)
        if (test) {
            println test as JSON
            println 'BeforeInsert...'
            throw new BusinessException("test....")
        }
    }

    @Subscriber
    void afterInsert(PostInsertEvent event) {
        Test test = test(event)
        if (test) {
            println test as JSON
            println 'afterInsert...'
            throw new BusinessException("test....")
        }
    }

    @Subscriber
    void afterUpdate(PostUpdateEvent event) {
        Test test = test(event)
        if (test) {
            println 'afterUpdate...'
        }
    }

    @Subscriber
    void afterDelete(PostDeleteEvent event) {
        Test test = test(event)
        if (test) {
            println 'afterDelete...'
        }
    }
}
